package com.example.mywood;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bean.CodeBean;
import bean.ContentDataBean;
import myapp.MyApp;
import myview.CountDownButton;
import util.MyLog;
import util.RequestManager;
import util.SystemStatusManager;

public class ForgetPwdActivity extends BaseActivity implements View.OnClickListener {



    private Context context;
    private EditText et_phone_bycode;
    private TextView tv_getcode;
    private CountDownButton tv_getcode2;
    private EditText et_code_bycode;
    private EditText et_pwd;
    private EditText et_pwd_again;
    private TextView tv_register;
    private MyApp myapp;
    private String apptype;
    private String textData;
    private ContentDataBean.DataBean textContent;
    private SharedPreferences sharedPreferences;
    private LinearLayout ll_bianma;
    private TextView tv_bianma;
    private LinearLayout ll_register;
    private LinearLayout ll_email_reg;
    private TextView tv_email_reg;
    private View view_email_line;
    private LinearLayout ll_mobile_reg;
    private TextView tv_mobile_reg;
    private View view_mobile_line;
    private String registertype = "email";
    private List<CodeBean.DataBean> temcodesList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_forgetpwd);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        initView();
        initLin();
        if ("0".equals(apptype)){
        }else if ("1".equals(apptype)){
            getCodeData();
        }

    }
    private void initView() {
        ll_bianma = findViewById(R.id.ll_bianma);
        tv_bianma = findViewById(R.id.tv_bianma);
        ll_register = findViewById(R.id.ll_register);
        ll_email_reg = findViewById(R.id.ll_email_reg);
        tv_email_reg = findViewById(R.id.tv_email_reg);
        view_email_line = findViewById(R.id.view_email_line);
        ll_mobile_reg = findViewById(R.id.ll_mobile_reg);
        tv_mobile_reg = findViewById(R.id.tv_mobile_reg);
        view_mobile_line = findViewById(R.id.view_mobile_line);


        et_phone_bycode = findViewById(R.id.et_phone_bycode);
        tv_getcode = findViewById(R.id.tv_getcode);
        tv_getcode2 = findViewById(R.id.tv_getcode2);
        et_code_bycode = findViewById(R.id.et_code_bycode);
        et_pwd = findViewById(R.id.et_pwd);
        et_pwd_again = findViewById(R.id.et_pwd_again);
        tv_register = findViewById(R.id.tv_register);
        TextView tv_title = findViewById(R.id.tv_title);

        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_title.setText(textContent.getForgetpwd_try());
            et_phone_bycode.setHint(textContent.getInput_account());
            et_code_bycode.setHint(textContent.getInput_code());
            tv_getcode2.setText(textContent.getGet_code());
            et_pwd.setHint(textContent.getInput_pwd());
            et_pwd_again.setHint(textContent.getInput_pwd_again());
            tv_register.setText(textContent.getDefine());



            if ("0".equals(apptype)){
                //木头
                ll_register.setVisibility(View.GONE);
                et_phone_bycode.setHint(textContent.getInput_phone());
                tv_bianma.setText("");
            }else if ("1".equals(apptype)){
                //熙然
                tv_bianma.setText("");
                ll_register.setVisibility(View.VISIBLE);
                tv_mobile_reg.setText(textContent.getPhone_number());
                tv_email_reg.setText(textContent.getEmail_address());
                et_phone_bycode.setHint(textContent.getInput_account());
            }
        }

    }

    private void initLin() {
        ll_bianma.setOnClickListener(this);
        ll_mobile_reg.setOnClickListener(this);
        ll_email_reg.setOnClickListener(this);
        tv_register.setOnClickListener(this);
        tv_getcode.setOnClickListener(this);
        tv_getcode2.setOnClickListener(this);
        et_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 禁止EditText输入空格
                if (charSequence.toString().contains(" ")) {
                    String[] str = charSequence.toString().split(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]);
                    }
                    et_pwd.setText(sb.toString());
                    et_pwd.setSelection(start);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_pwd_again.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 禁止EditText输入空格
                if (charSequence.toString().contains(" ")) {
                    String[] str = charSequence.toString().split(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]);
                    }
                    et_pwd_again.setText(sb.toString());
                    et_pwd_again.setSelection(start);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        et_phone_bycode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 禁止EditText输入空格
                if (charSequence.toString().contains(" ")) {
                    String[] str = charSequence.toString().split(" ");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < str.length; i++) {
                        sb.append(str[i]);
                    }
                    et_phone_bycode.setText(sb.toString());
                    et_phone_bycode.setSelection(start);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()){
            case R.id.tv_register:
                String phonestr = et_phone_bycode.getText().toString().trim();
                String code = et_code_bycode.getText().toString().trim();
                String pwd = et_pwd.getText().toString().trim();
                String surepwd = et_pwd_again.getText().toString().trim();
                if (pwd.equals(surepwd)){
                    register(phonestr,code,pwd);
                }else{
                    if (textContent!= null){
                        Toast.makeText(context,textContent.getPwd_error(),Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(context,getString(R.string.pwd_error),Toast.LENGTH_LONG).show();
                    }
                }
                /*ChatClient.getInstance().register("hanbaby", "111111", new Callback() {
                    @Override
                    public void onSuccess() {
                        MyLog.e("环信客服云","注册成功");
                    }

                    @Override
                    public void onError(int code, String error) {
                        MyLog.e("环信客服云","注册失败  "+code+"   error:"+error);
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });*/
                break;
            case R.id.tv_getcode2:
                String phone = et_phone_bycode.getText().toString().trim();
                getPhoneAuthCode(phone);
                break;
            case R.id.ll_mobile_reg:
                //手机号注册
                registertype = "mobile";
                ll_bianma.setVisibility(View.VISIBLE);
                tv_mobile_reg.setTextColor(getResources().getColor(R.color.color1E1934k));
                view_mobile_line.setVisibility(View.VISIBLE);
                tv_email_reg.setTextColor(getResources().getColor(R.color.color999));
                view_email_line.setVisibility(View.INVISIBLE);
                et_phone_bycode.setHint(textContent.getInput_phone());
                et_phone_bycode.setText("");
                break;
            case R.id.ll_email_reg:
                //邮箱注册
                registertype = "email";
                ll_bianma.setVisibility(View.GONE);
                tv_mobile_reg.setTextColor(getResources().getColor(R.color.color999));
                view_mobile_line.setVisibility(View.INVISIBLE);
                tv_email_reg.setTextColor(getResources().getColor(R.color.color1E1934k));
                view_email_line.setVisibility(View.VISIBLE);
                et_phone_bycode.setHint(textContent.getEnter_email());
                et_phone_bycode.setText("");
                break;
            case R.id.ll_bianma:
                //编码
                intent = new Intent(context,BianmaActivity.class);
                startActivityForResult(intent,1);
                break;
        }
    }


    /**
     * 发送验证码
     */
    private void getPhoneAuthCode(String phone) {
        String phonestr = et_phone_bycode.getText().toString().trim();
        String type = "1";
        if (phone.contains("@")){
            //说明是邮箱
            type = "0";
        }else{
            //说明是手机号
            type = "1";
        }
        String url = "";
        String bianmacode = tv_bianma.getText().toString().trim();
        bianmacode = bianmacode.replace("+","");
        HashMap<String, String> paramsMap = new HashMap<>();
        if ("0".equals(type)){
            url = myapp.getWebConfig() + "/api/ems/send";
            paramsMap.put("event", "resetpwd");
            paramsMap.put("email", phone);
            paramsMap.put("is_material", apptype);
        }else if ("1".equals(type)){
            url = myapp.getWebConfig() + "/api/sms/send";
            paramsMap.put("event", "mobilelogin");
            paramsMap.put("mobile", phone);
            paramsMap.put("is_material", apptype);
            paramsMap.put("country_code", bianmacode);
        }
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }
    /**
     * 注册
     */
    private void register(String phone,String code,String pwd) {
        String phonestr = "";
        String emailstr = "";
        String type = "";
        if (phone.contains("@")){
            emailstr = phone;
            type = "email";
        }else{
            phonestr = phone;
            type = "mobile";
        }
        String bianmacode = tv_bianma.getText().toString().trim();
        bianmacode = bianmacode.replace("+","");
        String url = myapp.getWebConfig() + "/api/user/resetpwd";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("type", type);
        paramsMap.put("mobile", phonestr);
        paramsMap.put("email", emailstr);
        paramsMap.put("newpassword", pwd);
        paramsMap.put("captcha", code);
        paramsMap.put("is_material", apptype);
        paramsMap.put("country_code", bianmacode);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    /*JSONObject data = jsonObject.getJSONObject("data");
                    JSONObject userinfo = data.getJSONObject("userinfo");

                    SharedPreferences spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
                    spuserInfo.edit().putString("username",userinfo.getString("username")).commit();
                    spuserInfo.edit().putString("nickname",userinfo.getString("nickname")).commit();
                    spuserInfo.edit().putString("mobile",userinfo.getString("mobile")).commit();
                    spuserInfo.edit().putString("score",userinfo.getString("score")).commit();
                    spuserInfo.edit().putString("token",userinfo.getString("token")).commit();
                    spuserInfo.edit().putString("user_id",userinfo.getString("user_id")).commit();
                    spuserInfo.edit().putString("level",userinfo.getString("level")).commit();*/
                    msg.obj = jsonObject.getString("msg");
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //此处可以根据两个Code进行判断，本页面和结果页面跳过来的值
        if (requestCode == 1 && resultCode == 3) {
            String result = data.getStringExtra("result");
            tv_bianma.setText("+"+result);
        }
    }
    public Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context,str,Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (textContent!=null){
                        Toast.makeText(context,textContent.getNet_error(),Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(context,getString(R.string.net_error),Toast.LENGTH_LONG).show();
                    }
                    break;
                case 2:
                    //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                    tv_getcode2.settime(120000);
                    if (tv_getcode2.isFinish()) {
                        //发送验证码请求成功后调用
                        tv_getcode2.start();
                    }
                    break;
                case 3:
                    //验证码登录结果
//                    intent = new Intent(context,MainActivity.class);
//                    startActivity(intent);
//                    myapp.destoryActivity("登陆页面");
                    String strs = (String) msg.obj;
                    Toast.makeText(context,strs,Toast.LENGTH_LONG).show();
                    finish();
                    break;
                case 4:

                    break;
                case 5:
                    if (temcodesList.size() > 0){
                        tv_bianma.setText("+"+temcodesList.get(0).getCode());
                    }
                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intentl = new Intent(context, LoginActivity.class);
                        context.startActivity(intentl);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
private boolean islogin = false;
    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    TextWatcher textChanged = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            // 禁止EditText输入空格
            if (charSequence.toString().contains(" ")) {
                String[] str = charSequence.toString().split(" ");
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < str.length; i++) {
                    sb.append(str[i]);
                }
                et_pwd.setText(sb.toString());
                et_pwd.setSelection(start);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    /**
     * 编码
     */
    private void getCodeData() {
        temcodesList.clear();

        String url = myapp.getWebConfig() + "/api/index/code";
        HashMap<String, String> paramsMap = new HashMap<>();
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temcodesList = new Gson().fromJson(data.toString(), new TypeToken<List<CodeBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }else{
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }


}
